<template>
	<view class="z-box" :style="`padding-top:${BarNavHeight}px`">
		<u-navbar :autoBack="true" leftIconColor="#000" title="二维码" :title-style="NavCss" bgColor="#f9f9f9"></u-navbar>
		<u-tabs :list="tabList" @click="switchTab" line-width="35"></u-tabs>
		<view class="print-container">
			<view class="qr-code">
				<canvas canvas-id="qrcode" :style="`width:${qrCodeSize}px; height:${qrCodeSize}px;`"></canvas>
			</view>
			<view class="item">
				<view class="label">作物类型：</view>
				<view class="val">{{ tabName }}</view>
			</view>
			<view class="item">
				<view class="label">重量(kg)：</view>
				<view class="val">{{ tabName === '土壤' ? printContent.soilWeight : printContent.cropWeight }}</view>
			</view>
			<view class="item">
				<view class="label">编码：</view>
				<view class="val">{{ tabName === '土壤' ? printContent.soilCode : printContent.cropCode }}</view>
			</view>
			<view class="item">
				<view class="label">采样人：</view>
				<view class="val">{{ printContent.samplingPerson }}</view>
			</view>
			<view class="item">
				<view class="label">采样时间：</view>
				<view class="val">{{ printContent.samplingTime }}</view>
			</view>
			<view class="item">
				<view class="label">地址：</view>
				<view class="val">{{ printContent.address }}</view>
			</view>
		</view>
		<view class="btns">
			<u-button type="primary" v-if="!isBLDConnected" text="蓝牙连接" @click="openBLDPicker" style="margin-right: 10px;"></u-button>
			<u-button type="success" v-else @click="disconnectBLD" style="margin-right: 10px;">断开连接</u-button>
			<u-button type="warning" text="打印" @click="print" style="margin-left: 10px;" :disabled="!isBLDConnected || isPrinting"></u-button>
		</view>
		<u-picker ref="BLDPicker" :show="showBLDPicker" :columns="BLDColumns" keyName="name" @confirm="setBLD" cancelText="重新扫描" @cancel="rescanBLD"></u-picker>
		<u-notify ref="notify"></u-notify>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import LayoutMix from '@/mixins/layout-mix.js'
	import NotifyMix from '@/mixins/notify-fix.js'
	import Util from "@/utils";
	import API from '@/api/index.js'
	import UQRCode from '@/sdk/uqrcode/uqrcode.js';
	import CTPL from "@/sdk/uni_ctpl_sdk/ctpl.js";
	export default {
		mixins: [LayoutMix, NotifyMix],
		data() {
			return {
				qrCodeSize: 0,
				tabList: [{
						name: '土壤'
					},
					{
						name: '农产品'
					}
				],
				tabName: '土壤',
				printContent: {},
				isBLDConnected: false, // 是否连接到蓝牙打印机设备
				showBLDPicker: false, // 是否显示蓝牙设备选择器
				BLDColumns: [
					[]
				],
				isPrinting: false,
			};
		},
		computed: {
			...mapState({
				device: state => state.printer.device
			}),
		},
		methods: {
			...mapMutations({
				setDevice: 'printer/setDevice'
			}),
			initQRWidth() {
				const that = this
				return new Promise((resolve) => {
					uni.getSystemInfo({
						success: function(info) {
							that.qrCodeSize = info.windowWidth * 0.9 - 40
							resolve(true)
						}
					});
				})
			},
			genQRCode() {
				UQRCode.make({
					canvasId: 'qrcode',
					componentInstance: this,
					text: '1111111',
					size: this.qrCodeSize,
					margin: 0,
					backgroundColor: '#ffffff',
					foregroundColor: '#000000',
					fileType: 'jpg',
					errorCorrectLevel: UQRCode.errorCorrectLevel.H,
					success: res => {}
				})
			},
			switchTab(item) {
				this.tabName = item.name
			},
			async fetchPrintContent(taskId) {
				uni.showLoading();
				const res = await API.CjRecordApi.getPrintContent(taskId);
				uni.hideLoading()
				if (res.code !== 200 || !res.data) {
					this.notifyFail('获取详情失败')
				}
				res.data.samplingTime = Util.dayjs(res.data.samplingTime).format("YYYY-MM-DD")
				this.printContent = res.data
			},
			async initBLD() {
				const that = this
				await CTPL.init();
				if (this.device.name) {
					CTPL.disconnect()
					uni.showLoading({
						title: '连接中'
					})
					setTimeout(() => {
						CTPL.connect(
							that.device,
							function success(res) {
								that.notifyOk('连接打印机成功')
								that.isBLDConnected = true
								uni.hideLoading()
							},
							function fail(err) {
								that.notifyFail('请连接打印机')
								that.setDevice({})
								that.isBLDConnected = false
								uni.hideLoading()
							}
						)
					}, 200)
				} else {
					that.notifyFail('请连接打印机')
					that.setDevice({})
					that.isBLDConnected = false
				}
				// 部分手机接受不到蓝牙设备需手动开启定位授权
				// uni.getLocation({
				//   type: 'gcj02',
				//   success (res) {
				//     console.log(res)
				//   }
				//  })
			},
			disconnectBLD() {
				CTPL.disconnect()
				this.isBLDConnected = false
			},
			async openBLDPicker() {
				this.scanBLD()
				this.showBLDPicker = true
			},
			scanBLD() {
				const that = this;
				that.BLDColumns[0] = []
				CTPL.discovery(function(res) {
					if (res.name.indexOf('CT220F') > -1) {
						that.BLDColumns[0] = that.BLDColumns[0].concat(res);
						that.$refs.BLDPicker.setColumnValues(0, that.BLDColumns[0])
					}
				});
			},
			rescanBLD() {
				this.scanBLD()
			},
			setBLD(val) {
				const that = this
				CTPL.connect(
					val.value[0],
					function success(res) {
						that.setDevice(val.value[0])
						that.isBLDConnected = true
						that.showBLDPicker = false
						that.notifyOk('连接打印机成功')
					},
					function fail(err) {
						that.notifyFail('请连接打印机')
					}
				)
			},
			print() {
				const that = this
				this.isPrinting = true
				uni.showLoading({
					title: '请等待..'
				})
				CTPL.setSize(45, 90)
				CTPL.clearCache()
				CTPL.drawQRCode(
					30, // 起始点 x
					90, // 起始点 y
					'H', // 纠错等级
					10, // 二维码格子宽度
					'M', // 二维码编码模式
					'M1', // 二维码码制
					'S7', // 蒙版等级
					this.tabName === '土壤' ? this.printContent.soilCode : this.printContent.cropCode // 内容
				)
				CTPL.clearCache()
				CTPL.drawText(
					30,
					360,
					0,
					1,
					1,
					`作物类型：${this.tabName}`
				)
				CTPL.clearCache()
				CTPL.drawText(
					30,
					395,
					0,
					1,
					1,
					`重量(kg)：${this.tabName === '土壤' ? this.printContent.soilWeight : this.printContent.cropWeight}`
				)
				CTPL.clearCache()
				CTPL.drawText(
					30,
					430,
					0,
					1,
					1,
					`编码：${this.tabName === '土壤' ? this.printContent.soilCode : this.printContent.cropCode}`
				)
				CTPL.clearCache()
				CTPL.drawText(
					30,
					465,
					0,
					1,
					1,
					`采样人：${this.printContent.samplingPerson}`
				)
				CTPL.clearCache()
				CTPL.drawText(
					30,
					500,
					0,
					1,
					1,
					`采样时间：${this.printContent.samplingTime}`
				)
				CTPL.clearCache()
				CTPL.drawText(
					30,
					535,
					0,
					1,
					1,
					`地址：${this.printContent.address}`
				)
				CTPL.setPrintCopies(1, 1)
				CTPL.execute()
				setTimeout(() => {
					that.isPrinting = false
					uni.hideLoading()
				}, 5000)
			},
		},
		async onLoad(query) {
			await this.initQRWidth()
			await this.fetchPrintContent(query.taskId)
			this.genQRCode()
			this.initBLD();
		},
		beforeDestroy() {
			if (this.isBLDConnected) {
				CTPL.disconnect()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.z-box {
		background-color: #f3f4f6;
		height: 100vh;

		.print-container {
			width: 90vw;
			margin-left: 5vw;
			background-color: #fff;
			border-radius: 6px;
			padding: 20px 20px 10px 20px;
			margin-top: 5px;

			.qr-code {
				margin-bottom: 20px;
			}

			.item {
				display: flex;
				font-size: 18px;
				line-height: 20px;
				margin-bottom: 10px;

				.label {
					color: gray;
					width: 90px;
				}

				.val {
					flex: 1;
					color: black;
				}
			}
		}

		.btns {
			padding: 19px;
			display: flex;
			justify-content: space-between;
		}
	}
</style>